//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Localization;
namespace DotNetNuke.Modules.Admin.Security
{
	partial class MemberServices : UserModuleBase
	{
		public delegate void SubscriptionUpdatedEventHandler(object sender, SubscriptionUpdatedEventArgs e);
		public event SubscriptionUpdatedEventHandler SubscriptionUpdated;
		private int RoleID = -1;
		private string FormatPrice(float price)
		{
			string _FormatPrice = Null.NullString;
			try
			{
				if (price != Null.NullSingle)
				{
					_FormatPrice = price.ToString("##0.00");
				}
				else
				{
					_FormatPrice = "";
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return _FormatPrice;
		}
		private ArrayList GetRoles(int portalId, int userId)
		{
			RoleController objRoles = new RoleController();
			return objRoles.GetUserRoles(portalId, userId, false);
		}
		private void Subscribe(int roleID, bool cancel)
		{
			RoleController objRoles = new RoleController();
			RoleInfo objRole = objRoles.GetRole(roleID, PortalSettings.PortalId);
			if (objRole.IsPublic && objRole.ServiceFee == 0.0)
			{
				objRoles.UpdateUserRole(PortalId, UserInfo.UserID, roleID, cancel);
				OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(cancel, objRole.RoleName));
			}
			else
			{
				if (!cancel)
				{
					Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID.ToString(), true);
				}
				else
				{
					Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID.ToString() + "&cancel=1", true);
				}
			}
		}
		private void UseTrial(int roleID)
		{
			RoleController objRoles = new RoleController();
			RoleInfo objRole = objRoles.GetRole(roleID, PortalSettings.PortalId);
			if (objRole.IsPublic && objRole.TrialFee == 0.0)
			{
				objRoles.UpdateUserRole(PortalId, UserInfo.UserID, roleID, false);
				OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName));
			}
			else
			{
				Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID.ToString(), true);
			}
		}
		protected string FormatExpiryDate(System.DateTime expiryDate)
		{
			string _FormatExpiryDate = Null.NullString;
			try
			{
				if (!Null.IsNull(expiryDate))
				{
					if (expiryDate > System.DateTime.Today)
					{
						_FormatExpiryDate = expiryDate.ToShortDateString();
					}
					else
					{
						_FormatExpiryDate = Localization.GetString("Expired", this.LocalResourceFile);
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return _FormatExpiryDate;
		}
		protected string FormatPrice(float price, int period, string frequency)
		{
			string _FormatPrice = Null.NullString;
			try
			{
				switch (frequency)
				{
					case "N":
					case "":
						_FormatPrice = Localization.GetString("NoFee", this.LocalResourceFile);
						break;
					case "O":
						_FormatPrice = FormatPrice(price);
						break;
					default:
						_FormatPrice = string.Format(Localization.GetString("Fee", this.LocalResourceFile), FormatPrice(price), period, Localization.GetString("Frequency_" + frequency, this.LocalResourceFile));
						break;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return _FormatPrice;
		}
		protected string FormatTrial(float price, int period, string frequency)
		{
			string _FormatTrial = Null.NullString;
			try
			{
				switch (frequency)
				{
					case "N":
					case "":
						_FormatTrial = Localization.GetString("NoFee", this.LocalResourceFile);
						break;
					case "O":
						_FormatTrial = FormatPrice(price);
						break;
					default:
						_FormatTrial = string.Format(Localization.GetString("TrialFee", this.LocalResourceFile), FormatPrice(price), period, Localization.GetString("Frequency_" + frequency, this.LocalResourceFile));
						break;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return _FormatTrial;
		}
		protected string FormatURL()
		{
			string _FormatURL = Null.NullString;
			try
			{
				string strServerPath;
				strServerPath = Request.ApplicationPath;
				if (!strServerPath.EndsWith("/"))
				{
					strServerPath += "/";
				}
				_FormatURL = strServerPath + "Register.aspx?tabid=" + TabId;
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return _FormatURL;
		}
		protected string ServiceText(bool Subscribed, DateTime expiryDate)
		{
			string _ServiceText = Null.NullString;
			try
			{
				if (!Subscribed)
				{
					_ServiceText = Localization.GetString("Subscribe", this.LocalResourceFile);
				}
				else
				{
					_ServiceText = Localization.GetString("Unsubscribe", this.LocalResourceFile);
					if (!Null.IsNull(expiryDate))
					{
						if (expiryDate < System.DateTime.Today)
						{
							_ServiceText = Localization.GetString("Renew", this.LocalResourceFile);
						}
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return _ServiceText;
		}
		protected bool ShowSubscribe(int roleID)
		{
			RoleController objRoles = new RoleController();
			bool _ShowSubscribe = Null.NullBoolean;
			RoleInfo objRole = objRoles.GetRole(roleID, PortalSettings.PortalId);
			if (objRole.IsPublic)
			{
				PortalController objPortals = new PortalController();
				PortalInfo objPortal = objPortals.GetPortal(PortalSettings.PortalId);
				if (objRole.ServiceFee == 0.0)
				{
					_ShowSubscribe = true;
				}
				else if (objPortal != null && !string.IsNullOrEmpty(objPortal.ProcessorUserId))
				{
					_ShowSubscribe = true;
				}
			}
			return _ShowSubscribe;
		}
		protected bool ShowTrial(int roleID)
		{
			RoleController objRoles = new RoleController();
			bool _ShowTrial = Null.NullBoolean;
			RoleInfo objRole = objRoles.GetRole(roleID, PortalSettings.PortalId);
			if (objRole.TrialFrequency == "N" || (objRole.IsPublic && objRole.ServiceFee == 0.0))
			{
				_ShowTrial = Null.NullBoolean;
			}
			else if (objRole.IsPublic && objRole.TrialFee == 0.0)
			{
				UserRoleInfo objUserRole = objRoles.GetUserRole(PortalId, UserInfo.UserID, roleID);
				if ((objUserRole == null) || (!objUserRole.IsTrialUsed))
				{
					_ShowTrial = true;
				}
			}
			return _ShowTrial;
		}
		public override void DataBind()
		{
			if (Request.IsAuthenticated)
			{
				grdServices.DataSource = GetRoles(PortalId, UserInfo.UserID);
				grdServices.DataBind();
				ServicesRow.Visible = (grdServices.Items.Count > 0);
			}
		}
		public void OnSubscriptionUpdated(SubscriptionUpdatedEventArgs e)
		{
			if (SubscriptionUpdated != null)
			{
				SubscriptionUpdated(this, e);
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdRSVP.Click += new EventHandler(cmdRSVP_Click);
			grdServices.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(grdServices_ItemCommand);

			try
			{
				lblRSVP.Text = "";
				if (Page.IsPostBack == false)
				{
					Localization.LocalizeDataGrid(ref grdServices, this.LocalResourceFile);
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdRSVP_Click(object sender, System.EventArgs e)
		{
			string code = txtRSVPCode.Text;
			bool blnRSVPCodeExists = false;
			if (!String.IsNullOrEmpty(code))
			{
				RoleController objRoles = new RoleController();
				ArrayList arrRoles = objRoles.GetPortalRoles(PortalSettings.PortalId);
				foreach (RoleInfo objRole in arrRoles)
				{
					if (objRole.RSVPCode == code)
					{
						objRoles.UpdateUserRole(PortalId, UserInfo.UserID, objRole.RoleID);
						blnRSVPCodeExists = true;
						OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName));
					}
				}
				if (blnRSVPCodeExists)
				{
					lblRSVP.Text = Localization.GetString("RSVPSuccess", this.LocalResourceFile);
					txtRSVPCode.Text = "";
				}
				else
				{
					lblRSVP.Text = Localization.GetString("RSVPFailure", this.LocalResourceFile);
				}
			}
			DataBind();
		}
		protected void grdServices_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			string commandName = e.CommandName;
			int roleID = Convert.ToInt32(e.CommandArgument);
			if (commandName == Localization.GetString("Subscribe", this.LocalResourceFile)
				|| commandName == Localization.GetString("Renew", this.LocalResourceFile))
			{
				Subscribe(roleID, false);
			}
			else if (commandName == Localization.GetString("Unsubscribe", this.LocalResourceFile))
			{
				Subscribe(roleID, true);
			}
			else if (commandName == Localization.GetString("Unsubscribe", this.LocalResourceFile))
			{
				Subscribe(roleID, true);
			}
			else if (commandName == "UseTrial")
			{
				UseTrial(roleID);
			}
			DataBind();
		}
		public class SubscriptionUpdatedEventArgs
		{
			private bool _cancel;
			private string _roleName;
			public SubscriptionUpdatedEventArgs(bool cancel, string roleName)
			{
				_cancel = cancel;
				_roleName = roleName;
			}
			public bool Cancel
			{
				get { return _cancel; }
				set { _cancel = value; }
			}
			public string RoleName
			{
				get { return _roleName; }
				set { _roleName = value; }
			}
		}
	}
}
